<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/29
 * Time: 14:38
 */

namespace common\models\Service;


use common\models\CommonFunction;
use common\models\DAO\Invest;
use common\models\DAO\Loan;
use common\models\DAO\LoanAttr;
use common\models\DAO\LoanAttrInfo;
use common\models\DAO\Overdue;
use common\models\DAO\UserExtinfo;
use common\models\User;

class InvestDetailService {
    /*
     * 取得投资项目详情信息并组装数据
     */
    public function getDetail($id){
        $invest  = Invest::find()->with('investInfo')->where(['id'=>$id])->asArray()->one();
        $user_id = $invest['userID'] ;

        //信用状况统计
        $credit_status = array(
            'loan_publish'   => 0, //发布借款数
            'loan_success'   => 0, //借款成功次数
            'loan_moneys'    => 0, //借款总金额
            'loan_pay_off'   => 0, //借款还清总数
            'overdue_count'  => 0, //逾期次数
            'overdue_moneys' => 0, //逾期金额
        );
        $invest_list = Invest::find()->where(['userID' => $user_id])->all();
        foreach($invest_list as $v){
            $credit_status['loan_publish'] ++;
            if($v['status'] == 2) $credit_status['loan_success'] ++;
            if($v['status'] == 3) $credit_status['loan_pay_off'] ++;
        }
        $credit_status['overdue_moneys'] = Overdue::find()->where(['userID' => $user_id])->sum('overAmount');
        $credit_status['overdue_count']  = Overdue::find()->where(['userID' => $user_id])->count();

        //借款人信息表
        $user_info = User::find()->where(['id' => $user_id])->asArray()->one();
		if(!$user_info)	return false;
        $user_sex_age = CommonFunction::getUserInfoByIdentity($user_info['identity']);
        $user_info['sex'] = $user_sex_age['sex'];
        $user_info['age'] = $user_sex_age['age'];
        $user_info['realName'] = CommonFunction::filterRealName($user_info['realName'], $user_info['identity']);

        $user_info_ext = UserExtinfo::find()->with('user')->where("userID = $user_id ")->asArray()->all();
        foreach($user_info_ext as $v) {
            $attr = LoanAttr::find()->where(['id' => $v['attrID']])->asArray()->one();
            if (!empty($v['content'])) {
                $data['user_info_ext'][$attr['attrName']] = $v['content'];
            }else {
                $attrInfo = LoanAttrInfo::find()->where(['id' => $v['attrInfoID']])->asArray()->one();
                $data['user_info_ext'][$attr['attrName']] = $attrInfo['infoName'];
            }
        }
        $data['loan'] = Loan::find()->with('loanInfo')->where(['id'=>$id])->asArray()->one();
        $data['invest']        = $invest;
        $data['user_info']     = $user_info;
        $data['credit_status'] =  $credit_status;
        return $data;
    }
}